import { defineComponent, reactive, onMounted } from 'vue'
import * as XLSX from 'xlsx'
import { readFile } from '../../utils/readFile'

export default defineComponent({
  emits: ['childClick'],
  props: {
    title: String,
    accept: String
  },
  setup(props, context) {
    const state = reactive({
      tempTableData: [{}],
      searchInput: { PageIndex: 1, PageSize: 10 },
      tableData: { data: [{}], total: 0 },
      dialogVisible: false,
      colunm: [{ key: '', lable: '' }]
    })
    onMounted(() => {
      console.log(state.dialogVisible)
    })
    const childMethod = data => {
      state.colunm = data
      state.tableData.data = []
      state.dialogVisible = true
    }
    const getData = () => {
      const tempData: any = []
      state.tempTableData.forEach((value, index) => {
        if (
          index >=
            (state.searchInput.PageIndex - 1) * state.searchInput.PageSize &&
          index < state.searchInput.PageIndex * state.searchInput.PageSize
        ) {
          tempData.push(value)
        }
      })
      state.tableData.data = tempData
      state.tableData.total = state.tempTableData.length
    }
    const cancel = () => {
      state.dialogVisible = false
    }
    const submit = () => {
      console.log(state.tempTableData)
      context.emit('childClick', state.tempTableData, state.colunm)
    }
    const uploadChange = async file => {
      let dataBinary = await readFile(file.raw)
      let workBook = XLSX.read(dataBinary, { type: 'binary', cellDates: true })
      let workSheet = workBook.Sheets[workBook.SheetNames[0]]
      let data: any = XLSX.utils.sheet_to_json(workSheet)

      let mycolunm = {}
      Object.setPrototypeOf(mycolunm, data[0])
      state.colunm = []
      for (let key in mycolunm) {
        state.colunm.push({ lable: key, key: key })
      }

      let tHeader = state.colunm.map(obj => obj.lable)
      let filterVal = state.colunm.map(obj => obj.key)
      tHeader.map(val => filterVal.map(obj => val[obj]))
      const tempData: any = []
      data.forEach(value => {
        const ob = {}
        tHeader.forEach((item, index) => {
          ob[filterVal[index]] = value[item].toString()
        })
        tempData.push(ob)
      })
      state.tempTableData = tempData
      getData()
    }
    return {
      state,
      childMethod,
      cancel,
      submit,
      uploadChange,
      getData
    }
  }
})
